<script lang="ts" setup>
import type { DialogModel, User } from '@/index.d';
import { getById, reSetDialogModel, urls, getReadonly, insertOne, updateOne } from '@/index';
import { type FormInstance, type FormRules } from 'element-plus';

const dialogModel = defineModel<DialogModel<User>>('dialogModel', { required: true });

const { insertForbidden, updateForbidden } = getReadonly(dialogModel.value);

const formData = reactive<User>({
  id: 0,
  gender: '空',
  educationLevel: '空'
});

//为用户邮箱绑定值
watch(
  () => formData.username,
  value => (formData.email = value + '@shanghai-electric.com')
);

const setUser = async (res: User) => {
  formData.creator = res.creator;
  formData.createTime = res.createTime;
  formData.updater = res.updater;
  formData.updateTime = res.updateTime;
  formData.id = res.id;
  formData.name = res.name;
  formData.username = res.username;
  formData.email = res.email;
  formData.workNo = res.workNo;
  formData.idCard = res.idCard;
  formData.phone = res.phone;
  formData.gender = res.gender;
  formData.educationLevel = res.educationLevel;
  formData.graduateSchool = res.graduateSchool;
  formData.graduateDate = res.graduateDate;
  formData.major = res.major;
  formData.departmentId = res.departmentId;
  formData.department = res.department; //不可被后端更新
  formData.headImageUuid = res.headImageUuid;
  formData.headImageUrl = res.headImageUrl;
  formData.dingdingWebhook = res.dingdingWebhook;
};

const resetUser = () => {
  reSetDialogModel(dialogModel);
  formData.id = 0;
  formData.gender = '空';
  formData.educationLevel = '空';
  delete formData.departmentId;
  delete formData.name;
  delete formData.username;
  delete formData.email;
  delete formData.workNo;
  delete formData.idCard;
  delete formData.phone;
  delete formData.graduateSchool;
  delete formData.graduateDate;
  delete formData.major;
  delete formData.headImageUuid;
  delete formData.headImageUrl;
  delete formData.dingdingWebhook;
};

watch(
  () => dialogModel.value.visible,
  value => {
    // 当打开窗口时，将父元素传递过来的主键填充到表单中去
    value && (formData.id = dialogModel.value.id as number);
    // 当关闭窗口时，重置表单中的数据
    !value && resetUser();
  },
  {
    immediate: true
  }
);

// 监控id的变化，当id为0，为新增窗口，无需从数据库取值填充，当id不为0时，为更新或者查看窗口，从数据库取值进行填充
watch(
  () => formData.id,
  async (value: number | undefined) => {
    if (value) {
      const res = await getById<User>(urls.user, value);
      res && setUser(res);
    }
  },
  {
    immediate: true
  }
);

const userFormRef = ref<FormInstance>();

interface UserFormRules {
  departmentId: number;
  name: string;
  username: string;
  workNo: string;
  phone: string;
  idCard: string;
}

// 表单校验规则;
const userFormRules = computed(() => {
  switch (dialogModel.value.type) {
    case 'view':
      return reactive({});

    case 'update':
      return reactive<FormRules<UserFormRules>>({
        departmentId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
        phone: [{ min: 11, max: 11, message: '手机号码应为11位', trigger: 'blur' }],
        idCard: [{ min: 18, max: 18, message: '身份证应为18位', trigger: 'blur' }]
      });

    case 'insert':
      return reactive<FormRules<UserFormRules>>({
        departmentId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '姓名长度应为2到10位之间', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '帐号不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '帐号长度应为2到10位之间', trigger: 'blur' }
        ],
        workNo: [
          { required: true, message: '工号不能为空', trigger: 'blur' },
          { min: 8, max: 8, message: '工号长度应为8位', trigger: 'blur' }
        ],
        phone: [{ min: 11, max: 11, message: '手机号码应为11位', trigger: 'blur' }],
        idCard: [{ min: 18, max: 18, message: '身份证应为18位', trigger: 'blur' }]
      });
  }
});

const saveUser = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl
    .validate()
    .then(async valid => {
      if (valid) {
        if (dialogModel.value.id === 0) {
          const res = (await insertOne(urls.user, formData)) as User;
          if (res) {
            setUser(res);
            dialogModel.value.id = res.id as number;
            dialogModel.value.type = 'update';
            dialogModel.value.change = true;
          }
        } else {
          const tempFormData: User = {
            id: formData.id,
            name: formData.name,
            username: formData.username,
            email: formData.email,
            workNo: formData.workNo,
            idCard: formData.idCard,
            phone: formData.phone,
            gender: formData.gender,
            departmentId: formData.departmentId,
            educationLevel: formData.educationLevel,
            graduateSchool: formData.graduateSchool,
            graduateDate: formData.graduateDate,
            dingdingWebhook: formData.dingdingWebhook,
            major: formData.major
          };

          const res = (await updateOne<User>(urls.user, tempFormData)) as User;

          if (res) {
            dialogModel.value.change = true;
            formData.updater = res.updater;
            formData.updateTime = res.updateTime;
          }
        }
      }
    })
    .catch(res => console.log(res));
};
</script>
<template>
  <hq-dialog-detail
    v-model:dialogModel="dialogModel"
    v-if="dialogModel.visible"
    @submit="saveUser(userFormRef)"
    :operation="formData"
    operate-record
  >
    <template #default>
      <el-card shadow="hover">
        <template #header>基本信息</template>
        <template #default>
          <hq-form :model="formData" :rules="userFormRules" ref="userFormRef">
            <el-row :gutter="5">
              <hq-col v-show="false">
                <el-form-item label="序号" prop="id">
                  <el-input v-model.number="formData.id" readonly />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="部门" prop="departmentId">
                  <el-input
                    v-if="dialogModel.type === 'view'"
                    :value="formData.department?.label"
                    readonly
                  />
                  <HqCascaderDepartment v-else v-model:current="formData.departmentId" />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="姓名" prop="name">
                  <el-input v-model.trim="formData.name" :readonly="insertForbidden" />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="账号" prop="username">
                  <el-input
                    placeholder="请输入账号"
                    v-model.trim="formData.username"
                    :readonly="insertForbidden"
                  />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="工号" prop="workNo">
                  <el-input v-model.trim="formData.workNo" :readonly="insertForbidden" />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model.trim="formData.email" readonly />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="身份证" prop="idCard">
                  <el-input
                    v-model.trim="formData.idCard"
                    :readonly="updateForbidden"
                    show-word-limit
                    minlength="18"
                    maxlength="18"
                  />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="手机" prop="phone">
                  <el-input
                    v-model.trim="formData.phone"
                    :readonly="updateForbidden"
                    show-word-limit
                    minlength="11"
                    maxlength="11"
                  />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="性别" prop="gender">
                  <el-input v-if="dialogModel.type === 'view'" :value="formData.gender" readonly />
                  <el-select v-else v-model="formData.gender" :disabled="updateForbidden">
                    <HqGenderOptions />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="学历" prop="educationLevel">
                  <el-input
                    v-if="dialogModel.type === 'view'"
                    :value="formData.educationLevel"
                    readonly
                  />
                  <el-select
                    v-else
                    v-model="formData.educationLevel"
                    :disabled="updateForbidden"
                    clearable
                  >
                    <HqEducationLevelOptions />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="毕业学校" prop="graduateSchool">
                  <el-input v-model.trim="formData.graduateSchool" :readonly="updateForbidden" />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="专业" prop="major">
                  <el-input v-model.trim="formData.major" :readonly="updateForbidden" />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="毕业日期" prop="graduateDate">
                  <el-input
                    v-if="dialogModel.type === 'view'"
                    :value="formData.graduateDate"
                    readonly
                  />
                  <el-date-picker
                    v-else
                    v-model="formData.graduateDate"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :readonly="updateForbidden"
                  />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="钉钉" prop="dingdingWebhook">
                  <el-input v-model.trim="formData.dingdingWebhook" :readonly="updateForbidden" />
                </el-form-item>
              </hq-col>
            </el-row>
          </hq-form>
        </template>
      </el-card>
      <el-card shadow="hover" v-if="formData.headImageUuid">
        <template #header>用户头像</template>
        <template #default>
          <hq-upload-avatar
            :key-word="formData.headImageUuid"
            :disabled="dialogModel.type === 'view'"
          />
        </template>
      </el-card>
    </template>
  </hq-dialog-detail>
</template>
<style lang="scss" scoped></style>
